package com.gmail.dengtao.joe.group.packet;

import java.nio.ByteBuffer;
import java.util.Arrays;

import com.gmail.dengtao.joe.commons.util.ByteUtils;

public class DefaultPacketImpl implements Packet {

	// Packet Head
	private int len = 0;// total length
	private int type; // packet type
	private int pn; // packet number
	private int sn; // serial number
	private byte mf; // more packet flag

	// Packet Body
	private byte[] data;// data
	
	public DefaultPacketImpl(int type, int pn, int sn, byte mf, byte[] data) {
		this.type = type;
		this.pn = pn;
		this.sn = sn;
		this.mf = mf;
		this.data = data;
		this.len = ByteUtils.sizeOf(len, type, pn, sn, mf, data);
	}

	/**
	 * @return whether this packet has more packet
	 * @since 1.0
	 */
	public byte getMorePacket() {
		return mf;
	}
	
	/**
	 * @return whether this packet has more packet
	 * @since 1.0
	 */
	public boolean hasMorePacket() {
		if (mf == 1) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * @return this packet's serial number
	 * @since 1.0
	 */
	public int getSerialNumber() {
		return sn;
	}
	
	/**
	 * @return this packet's packet number
	 * @since 1.0
	 */
	public int getPacketNumber() {
		return pn;
	}
	
	/**
	 * @return Length of this packet
	 * @since 1.0
	 */
	public int getLength() {
		return len;
	}

	public void setData(byte[] data) {
		this.data = data;
		this.len = ByteUtils.sizeOf(len, type, pn, sn, mf, this.data);
	}
	
	/**
	 * Serializes the ChannelData object into a byte[] array
	 * @return
	 * @since 1.0
	 */
	public byte[] getData() {
		return data;
	}
	
	/**
	 * @return this packet's packet type
	 * @since 1.0
	 */
	public int getType() {
		return type;
	}
	
	/**
     * Shallow clone, what gets cloned depends on the implementation
     * @return ChannelPacket
     */
	public Object clone() {
		return new DefaultPacketImpl(type, pn, sn, mf, data);
	}

	public byte[] toBytes() {
		ByteBuffer buffer = ByteBuffer.allocate(len);
		buffer.putInt(len);
		buffer.putInt(type);
		buffer.putInt(pn);
		buffer.putInt(sn);
		buffer.putInt(mf);
		buffer.put(data);
		return buffer.array();
	}

	@Override
	public String toString() {
		return "DefaultPacketImpl [len=" + len + ", type=" + type + ", pn="
				+ pn + ", sn=" + sn + ", mf=" + mf + ", data="
				+ Arrays.toString(data) + "]";
	}
	
}
